package cn.microservices.cloud.common.web.handlers;

import cn.microservices.cloud.common.core.constant.LoginConstant;
import cn.microservices.cloud.common.core.utils.Response;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 对所有的controller进行拦截，不是通过网关过来的接口调用都不予通过
 */
@Slf4j
@Component
public class GatewayInterceptor implements HandlerInterceptor {

    @Value("${microservices.header.from}")
    public String from;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {
        String secretKey = request.getHeader(LoginConstant.FROM);
        String url = request.getRequestURI();
        log.info("网关拦截处理= {}",url);
        if(StringUtils.isEmpty(secretKey)||!secretKey.equals(from)){
            response.setContentType("application/json; charset=utf-8");
            PrintWriter writer = response.getWriter();

            writer.write(JSONObject.toJSONString(Response.errorMsg("非法访问")));
            return false;
        }
        return true;
    }

}